niu
<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="display" label="显示">
          <el-select v-model="queryParams.display" clearable style="width: 100px">
            <el-option label="显示" value="true" />
            <el-option label="隐藏" value="false" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="primary" plain icon="plus" @click="handleOpenDialog()">新增</el-button>
          <el-button
            type="danger"
            icon="delete"
            :disabled="selectIds.length === 0"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableDatas"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        class="data-table__content"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="imageUrl" label="图标" min-width="100">
          <template #default="scope">
            <img
              v-if="scope.row.imageUrl"
              :src="scope.row.imageUrl"
              style="width: 100px; height: 30px"
            />
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="name" width="150" />
        <el-table-column label="关联商品" prop="relatedName" width="150" />
        <el-table-column label="描述" align="center" min-width="150" prop="remark" />
        <el-table-column label="显示" align="center" min-width="150" prop="display">
          <template #default="scope">
            <el-switch
              v-model="scope.row.display"
              active-text="显示"
              inactive-text="隐藏"
              inline-prompt
              :inactive-value="false"
              :active-value="true"
              @change="updateDisplay(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 客户表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="name">
          <el-input v-model="formData.name" placeholder="请输入商品banner标题" />
        </el-form-item>

        <el-form-item label="关联商品" prop="relatedId">
          <el-autocomplete
            v-model="chooseGoods"
            clearable
            :fetch-suggestions="queryGoods"
            value-key="label"
            placeholder="请选择关联商品"
            @select="handleGoodsSelect"
          ></el-autocomplete>
        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入商品banner描述" />
        </el-form-item>

        <el-form-item label="图片" prop="attachmentIds">
          <MultiImageUpload
            :model-value="formData.attachmentIds"
            business-type="goods_banner"
            :limit="1"
            :file-types="['image/jpeg', 'image/png']"
            :max-size="2"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app.store";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import AttachUtil from "@/utils/attachUtil";
import QueryString from "qs";
import type { ElTable } from "element-plus";
const dataTableRef = ref<InstanceType<typeof ElTable>>();

import GoodsBannerAPI, {
  GoodsBannerPageQuery,
  GoodsBannerForm,
  GoodsBannerPageVO,
} from "@/api/goods/banner.api";
import GoodsAPI from "@/api/goods/goods.api";

defineOptions({
  name: "GoodsBanner",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const roleFormRef = ref();
const chooseGoods = ref("");
const loading = ref(false);
const total = ref(0);
// 选中的商品ID
const selectIds = ref<number[]>([]);
const formData = reactive<GoodsBannerForm>({
  attachmentIds: [],
});
const goodsOptions = ref<OptionType[]>([]);
const queryGoods = (queryString: string, cb: (arg: any) => void) => {
  if (!QueryString) {
    return goodsOptions.value;
  }
  const results = goodsOptions.value.filter((item: OptionType) => {
    if (item.label && item.label.toLowerCase().indexOf(queryString.toLowerCase()) === 0) {
      return true;
    }
    return false;
  });
  cb(results);
};

const handleGoodsSelect = (item: Record<string, any>) => {
  formData.relatedId = item.value;
};

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

const queryParams = reactive<GoodsBannerPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 客户表格数据
const tableDatas = ref<GoodsBannerPageVO[]>();

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

const rules = reactive({
  name: [{ required: true, message: "请输入商品banner标题", trigger: "blur" }],
  relatedId: [{ required: true, message: "请选择关联的商品", trigger: "blur" }],
  attachmentIds: [{ required: true, message: "请上传商品banner图片", trigger: "blur" }],
});

// 获取数据
function fetchData() {
  loading.value = true;
  GoodsBannerAPI.getPage(queryParams)
    .then((data) => {
      tableDatas.value = data.list;
      total.value = data.total;
      tableDatas.value.forEach((item) => {
        item.imageUrl = AttachUtil.getFilePreview(item.attachId || "");
      });
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 打开商品banner信息弹窗
async function handleOpenDialog(roleId?: string) {
  if (roleId) {
    dialog.title = "修改商品banner信息";
    await GoodsBannerAPI.getFormData(roleId)
      .then((data) => {
        Object.assign(formData, data);
        chooseGoods.value = data.relatedName || "";
        formData.attachmentIds = [data.attachId || ""];
      })
      .finally(() => {
        dialog.visible = true;
      });
  } else {
    dialog.visible = true;
    dialog.title = "新增商品banner信息";
  }
}

// 提交商品banner信息表单
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (formData.attachmentIds && formData.attachmentIds.length > 0) {
      formData.attachId = formData.attachmentIds[0];
    }
    if (valid) {
      loading.value = true;
      const houseId = formData.id;
      if (houseId) {
        GoodsBannerAPI.update(houseId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        formData.id = "";
        GoodsBannerAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  formData.id = undefined;
  formData.name = "";
  formData.relatedId = "";
  formData.remark = "";
  formData.attachmentIds = [];
  chooseGoods.value = "";
}

// 删除客户
function handleDelete(id?: string) {
  const ids = [id || selectIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除商品?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      GoodsBannerAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

const updateDisplay = (row: GoodsBannerPageVO) => {
  GoodsBannerAPI.updateDisplay(row.id || "0", row.display || false)
    .then(() => {
      ElMessage.success("修改成功");
    })
    .catch(() => {
      ElMessage.error("修改失败");
    });
};

const loadAllOptions = async () => {
  await GoodsAPI.getOptions().then((res) => {
    goodsOptions.value = res;
  });
};

onMounted(() => {
  handleQuery();
  loadAllOptions();
});
</script>
